package com.finalist.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.util.Assert;

/**
 * httpclient处理类
 * @author pengyb
 *
 */
public class HttpClientToolUtils
{

    public static String postXML(String url, String xml)
    {
        Assert.hasText(url);
        String result = null;
        HttpClient httpClient = new DefaultHttpClient();
        try
        {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(xml, ContentType.create("text/xml", "UTF-8")));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
            EntityUtils.consume(httpEntity);
        }
        catch (ClientProtocolException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            httpClient.getConnectionManager().shutdown();
        }
        return result;
    }

    public static String HttpPost(String url, List<NameValuePair> paramlist) throws Exception
    {
        Logger log = Logger.getLogger(ConstConfigUtil.class);
        String line = "";
        try
        {
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url);

            httpPost.setEntity(new UrlEncodedFormEntity(paramlist, "UTF-8"));

            HttpResponse httpResponse = httpClient.execute(httpPost);

            HttpEntity entity = httpResponse.getEntity();

            if (entity != null)
            {
                InputStream in = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                line = reader.readLine();
                in.close();
            }
            String requestUrl = url + paramlist;
            System.out.println(getRequestUrl(requestUrl));
            System.out.println(getRequestUrl(requestUrl));
            log.info("访问接口的url为:" + getRequestUrl(requestUrl));
            httpClient.getConnectionManager().shutdown();//关闭httpclient连接
        }
        catch (UnsupportedEncodingException e)
        {
            throw new Exception("httpClient访问编码格式异常");
        }
        catch (ClientProtocolException e)
        {
            throw new Exception("httpClient访问客服端协议异常");
        }
        catch (IOException e)
        {
            throw new Exception("httpClient访问IO异常");
        }

        return line;
    }

    public static String getRequestUrl(String requestUrl)
    {
        requestUrl = requestUrl.replace("\",\"", "\"$\"").replace(", ", "&").replace("$", ",");
        requestUrl = replaceFirstLetter(requestUrl, "&", "[");
        requestUrl = replaceLetter(requestUrl, "");
        return requestUrl;
    }

    /**
     * 替换字符串中首字符串
     * @param src   字符串
     * @return      首字母大写后的字符串
     */
    public static String replaceFirstLetter(String src, String des, String org)
    {
        if (src.indexOf(org) == 0)
        {
            src = des + src.substring(1);
        }
        else
        {
            src = src.substring(0, src.indexOf(org)) + des + src.substring(src.indexOf(org) + 1);
        }
        return src;
    }

    /**
     * 替换字符串中最后字符串
     * @param src   字符串
     * @return      首字母大写后的字符串
     */
    public static String replaceLetter(String src, String des)
    {
        return src.substring(0, src.length() - 1) + des;
    }
}
